package IO;

import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;

public class PipeInputStreamTest {

    //管道输出流线程
    private static class Sender extends Thread {
        private PipedOutputStream out = new PipedOutputStream();

        public PipedOutputStream getOutputStream() {
            return out;
        }

        @Override
        public void run() {
            try {
                for (char c : new Character[]{'h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd'}) {
                    out.write(c);
                }
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }

    //管道输入流线程
    private static class Receiver extends Thread {
        private PipedInputStream in;

        public Receiver(Sender sender) throws IOException {
            in = new PipedInputStream(sender.getOutputStream());
        }

        @Override
        public void run() {
            try {
                int data;
                while ((data = in.read()) != -1) {
                    System.out.print((char) data);
                }
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    //主函数
    public static void main(String[] args) throws IOException {
        Sender sender = new Sender();
        Receiver receiver = new Receiver(sender);
        sender.start();
        receiver.start();
    }
}
